package com.kl.modular.sysman.system.controller;

import com.alibaba.fastjson.JSON;
import com.kl.component.shiro.AuthLockException;
import com.kl.component.shiro.CaptchaUsernamePasswordToken;
import com.kl.component.shiro.IncorrectCaptchaException;
import com.kl.component.shiro.RoleNotHaveAuthException;
import com.kl.modular.common.controller.BaseController;
import com.kl.modular.common.response.ResponseBase;
import com.kl.modular.system.dao.bo.LoginBo;
import com.kl.modular.system.service.api.ISystemLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 登陆 
 * @author xrp_zjb
 * @date 2016/1/2 17:24
 * 
 */
@Controller
public class LoginController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private ISystemLogService systemLogService;

	/**
	 * 登陆主界面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/sysman/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request){

		return "/index.jsp";
	}

	/**
	 * 登陆
	 * @param loginBo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/sysman/loginIn", method = RequestMethod.POST)
	@ResponseBody
	public String loginIn(LoginBo loginBo, HttpServletRequest request) throws Exception{
		ResponseBase responseBase = new ResponseBase();
		responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
		// 数据有效性验证
		if(loginBo == null){
			logger.info("登陆 loginBo == null");
			responseBase.setMsg("请输入用户名与密码");
			return JSON.toJSONString(responseBase);
		}
		if(StringUtils.isEmpty(loginBo.getUserName())){
			logger.info("登陆 loginBo.userName == null");
			responseBase.setMsg("请输入用户名");
			return JSON.toJSONString(responseBase);
		}
		if(StringUtils.isEmpty(loginBo.getPassword())){
			logger.info("登陆 loginBo.password == null");
			responseBase.setMsg("请输入密码");
			return JSON.toJSONString(responseBase);
		}
		if(StringUtils.isEmpty(loginBo.getValidatedCode())){
			logger.info("登陆 loginBo.validatedCode == null");
			responseBase.setMsg("请输入验证码");
			return JSON.toJSONString(responseBase);
		}
		try {
			logger.info("登陆：" + loginBo.getUserName());
			Subject currentUser = SecurityUtils.getSubject();
			CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(
					loginBo.getUserName(), loginBo.getPassword(), false, request.getRemoteAddr(), loginBo.getValidatedCode());
			token.setType(CaptchaUsernamePasswordToken.TYPE_SYS);
			token.setRememberMe(true);
			currentUser.login(token);
			if (!currentUser.isAuthenticated())
				token.clear();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg("用户或密码错误");
		} catch (IncorrectCaptchaException ice) {
			ice.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg("验证码错误，请重新输入");
		}catch (IncorrectCredentialsException ice) {
			ice.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg("用户或密码错误");
		} catch (AuthLockException authe){
			authe.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg("用户已被锁定,无法登录");
		} catch (RoleNotHaveAuthException ae) {
			ae.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg(ae.getMessage());
		}catch (AuthenticationException ae) {
			ae.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			responseBase.setMsg("用户或密码错误");
		}catch (Exception e) {
			e.printStackTrace();
			responseBase.setStatus(ResponseBase.RESPONSE_STATUS_ERROR);
			responseBase.setMsg("系统错误");
		} finally {
			String jsonStr = JSON.toJSONString(responseBase);
			return jsonStr;
		}
	}
	
	/**
	 * 退出
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/sysman/loginout" , method = RequestMethod.GET)
	public String loginout(HttpServletRequest request){
		removeShiroSession();
		return "redirect:/sysman/login.do";
	}
	
	/**
	 * 登录主界面
	 * @return
	 */
	@RequestMapping(value = "/sysman/back/login" , method = RequestMethod.GET)
	public String loginIndex(){	
		return "/index.jsp";
	}
}
